package com.tvunetworks.center.device.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.util.Map;
/**
 * @program: tvucc-aggregator
 * @author lebronchen
 * @create: 2020-02-19 12:46
 **/
@Slf4j
@Component
@Configuration
public class HttpClientKeepAliveUtil implements InitializingBean {
    @Value("${maxTotal}")
    private static int MAXTOTAL=100;
    @Value("${httpconnectTimeout}")
    private static int HTTPCONNECTTIMEOUT=3000;
    @Value("${defaultMaxPerRoute}")
    private static int DEFAULTMAXPERROUTE=2;
    @Value("${connectionRequestTimeout}")
    private static int CONNECTIONREQUESTTIMEOUT=3000;
    @Value("${socketTimeout }")
    private static int SOCKETTIMEOUT=3000 ;
    @Value("${routerServerAuthorization}")
    private static String ROUTERSERAUTHORIZATION;
    private  static final  Logger LOGGER = LoggerFactory.getLogger(HttpClientKeepAliveUtil.class);
//    private static int maxTotal;//默认最大连接数
//    private static int defaultMaxPerRoute;//默认每个主机的最大链接数
//    private static int connectionRequestTimeout;//默认请求超时时间
//    private static int httpconnectTimeout;//默认链接超时时间
//    private static int socketTimeout;//默认socket超时时间
    private HttpRequestRetryHandler httpRequestRetryHandler = new DefaultHttpRequestRetryHandler();//默认不进行重试处理
    private CloseableHttpClient httpClient;
    public HttpClientKeepAliveUtil(){

    }
//    public HttpClientKeepAliveUtil(int maxTotal, int defaultMaxPerRoute, int connectionRequestTimeout, int httpconnectTimeout, int socketTimeout ){
//            this.maxTotal=maxTotal;
//            this.defaultMaxPerRoute=defaultMaxPerRoute;
//            this.connectionRequestTimeout=connectionRequestTimeout;
//            this.httpconnectTimeout=httpconnectTimeout;
//            this.socketTimeout=socketTimeout;
//    }

/*    *//**
     *
     * @param args  args
     * @throws Exception 编译异常
     *//*
    public static void main(String[] args) throws Exception {
        HttpClientKeepAliveUtil httpClientKeepAliveUtil = new HttpClientKeepAliveUtil();
        String url = "http://10.10.20.20:6535/status";
        for(int i=0;i<1000;i++){

//            String res = httpClientKeepAliveUtil.sendGet(url,null);
//            System.out.println(res);
        }

    }*/

    /**
     *
     * @param url url
     * @param params params
     * @param auth auth
     * @return String
     * @throws Exception 编译异常
     */
    public   String sendGet(String url, Map<String, Object> params,String auth) throws Exception {
        StringBuffer sb = new StringBuffer(url);
        if(!CollectionUtils.isEmpty(params)) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                sb.append(entry.getKey())
                        .append("=")
                        .append(entry.getValue())
                        .append("&");
            }
        }
        // no matter for the last '&' character
        HttpGet httpget = new HttpGet(sb.toString());
        httpget.addHeader("Authorization",auth);
        config(httpget,auth);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpget, HttpClientContext.create());
            System.out.println("======"+httpClient);
        } catch (IOException e) {
            LOGGER.error("httpclient error:"+e.getMessage());
            log.error("msg:{},e:{}",e.getMessage(),e);
        }
        if (response!=null) {
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "utf-8");
        }
        return  null;
    }


    private  void init() {
        ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
        LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf)
                .register("https", sslsf)
                .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
        // 设置最大连接数
        cm.setMaxTotal(MAXTOTAL);
        // 设置每个路由的默认连接数
        cm.setDefaultMaxPerRoute(DEFAULTMAXPERROUTE);

        //连接保持时间
        ConnectionKeepAliveStrategy myStrategy = new ConnectionKeepAliveStrategy() {
            public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                // Honor 'keep-alive' header
                HeaderElementIterator it = new BasicHeaderElementIterator(
                        response.headerIterator(HTTP.CONN_KEEP_ALIVE));
                while (it.hasNext()) {
                    HeaderElement he = it.nextElement();
                    String param = he.getName();
                    String value = he.getValue();
                    if (value != null && param.equalsIgnoreCase("timeout")) {
                        try {
                            return Long.parseLong(value) * 1000;
                        } catch(NumberFormatException ignore) {
                        }
                    }
                }
                return 30 * 1000;
            }
        };

        this.httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .setRetryHandler(httpRequestRetryHandler)
                .setKeepAliveStrategy(myStrategy)
                .build();

    }

    /**
     * http头信息的设置
     *
     * @param httpRequestBase
     */
    private static void config(HttpGet httpRequestBase,String auth) {
        httpRequestBase.setHeader("User-Agent", "Mozilla/5.0");
        httpRequestBase.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");
        httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
        httpRequestBase.setHeader("connection", "Keep-Alive");
        httpRequestBase.setHeader("Authorization ", auth);
        LOGGER.error(auth);
//        httpRequestBase.addHeader("Authorization", "Basic dHZ1OlI1Nl55VzQ0bA==");
        // 配置请求的超时设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECTIONREQUESTTIMEOUT)
                .setConnectTimeout(HTTPCONNECTTIMEOUT)
                .setSocketTimeout(SOCKETTIMEOUT).setContentCompressionEnabled(false)
                .build();
        httpRequestBase.setConfig(requestConfig);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    /**
     * 请求重试处理
     */
    private static final class DefaultHttpRequestRetryHandler implements HttpRequestRetryHandler

    {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 5) {// 如果已经重试了5次，就放弃
                return false;
            }
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接，那么就重试
                return true;
            }
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                return false;
            }
            if (exception instanceof InterruptedIOException) {// 超时
                return false;
            }
            if (exception instanceof UnknownHostException) {// 目标服务器不可达
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                return false;
            }
            if (exception instanceof SSLException) {// ssl握手异常
                return false;
            }

            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            // 如果请求是幂等的，就再次尝试
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    }


}
